<template>
  <QfPage title="题库管理">
    <template #hd>
      <el-row>
        <el-col :span="5">
          <el-button @click="showAddDialog = true"> 新增</el-button>
        </el-col>
        <el-col :span="7">
          <el-input v-model="keyword" placeholder="请输入你要搜索的问题" />
        </el-col>
        <el-col :span="6">
          开始时间
          <el-date-picker
            :disabled-date="countStartTime"
            v-model="stime"
            type="date"
            placeholder="Pick a day"
          />
        </el-col>
        <el-col :span="6">
          结束
          <el-date-picker
            :disabled-date="countEndTime"
            v-model="etime"
            type="date"
            placeholder="Pick a day"
          />
        </el-col>
      </el-row>
    </template>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="问题id" width="180" />
      <el-table-column prop="title" label="问题标题" width="180" />
      <el-table-column prop="createdAt" label="创建时间">
        <template #default="{ row }">
          {{ formatTime(row.createdAt, 'YYYY-MM-DD HH:mm') }}
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <template #ft>
      <el-pagination
        small
        background
        layout="prev, pager, next,sizes"
        :total="total"
        class="mt-4"
        :page-sizes="[5, 10, 30, 50]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </template>
    <!-- 添加问题的弹窗 -->
    <el-dialog v-model="showAddDialog" title="新增一个问题" fullscreen width="900px" center>
      <el-form :model="questionInfo" ref="addForm" label-width="100px">
        <el-form-item label="公司名称">
          <el-input v-model="questionInfo.companyName" disabled>
            <template #suffix>
              <button @click="showCompanyList = true">选择公司</button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="questionInfo.title" />
        </el-form-item>
        <el-form-item>
          <vue-qrcode
            :value="`http://127.0.0.1:8080/#/uploadimg?uuid=${uuid}`"
            :options="{ width: 200 }"
          ></vue-qrcode>
        </el-form-item>
        <el-form-item label="问题描述">
          <v-md-editor
            ref="editor"
            v-model="questionInfo.content"
            height="400px"
            :disabled-menus="[]"
            @upload-image="handleUploadImage"
          ></v-md-editor>
        </el-form-item>
        <el-form-item label="标签"> </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirm">添加</el-button>
      </template>
      <!-- 公司选择的组件 -->
      <companyPicker :visible="showCompanyList" @change="handleCompanyChange"></companyPicker>
    </el-dialog>
  </QfPage>
</template>

<script>
import axios from 'axios';
import io from 'socket.io-client';
import shortid from 'shortid'; // 生成一个唯一id
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import _ from 'lodash'; // 引入lodash 方便快速实现防抖
import { addQuestion, getQuestList } from '@/api/qa';

export default {
  name: 'qaPage',
  data() {
    return {
      stime: new Date(),
      etime: null,
      keyword: '',
      tableData: [],
      showAddDialog: false,
      showCompanyList: false,
      questionInfo: {
        companyName: '',
        companyId: '',
        title: '',
        content: '',
        tags: '',
        uid: '',
      },
      sc: null, // socket对象
      uuid: '',
      total: 0,
      limit: 5,
      curPage: 1,
    };
  },
  created() {
    // this.getList();
    this.uuid = shortid.generate();
    console.log('uuid', this.uuid);
  },
  mounted() {
    this.initSocket();
    this.getList();
  },
  beforeUnmount() {
    //  记得在组件销毁的时候一并的移除socket
    this.sc.disconnect();
  },
  computed: {
    skip() {
      return (this.curPage - 1) * this.limit;
    },
  },
  watch: {
    keyword(nv) {
      console.log('搜索的关键字发生了变化', nv);
      this.curPage = 1; // 页码重置为1
      this.getList();
    },
    stime(nv) {
      console.log('stime', nv);
    },
  },
  methods: {
    countEndTime(time) {
      const t = time.getTime();
      // 开始时间之前的不能选

      const st = this.stime.getTime();

      // 今天之后的不能选
      const d = new Date();
      d.setHours(23, 59, 59, 99);
      const lt = d.getTime();
      if (t > lt || st > t) return true;
      return false;
    },
    handlePageChange(res) {
      console.log('页面发生了变化', res);
      this.curPage = res;
      this.getList();
    },
    handleSizeChange(res) {
      console.log('每页条数发生变化', res);
      this.limit = res;
      this.getList();
    },
    initSocket() {
      // 创建一个socket链接
      this.sc = io('http://127.0.0.1:3030');

      // this.sc.emit(); 原生的websocket sc.send()
      // connect是 socket内置事件
      this.sc.on('connect', () => {
        console.log('socket链接成功');
      });

      //  newupload 是一个自定义事件
      this.sc.on(`newupload${this.uuid}`, (res) => {
        console.log('有图片上传成功', res);
        const url = res.fileList[0].response.msg;
        // 把图片插入到我们的编辑器当中
        this.$refs.editor.insert((selected) => ({
          // 要插入的文本
          text: `![Description](${url})`,
        }));
        // this.$refs.editor.insert(`![Description](${url})`);
      });
    },
    handleCompanyChange(res) {
      console.log('选择的公司是', res);
      this.questionInfo.companyName = res.name;
      this.questionInfo.companyId = res.id;
      this.showCompanyList = false; // 关闭弹窗
    },
    async confirm() {
      console.log('我是添加的操作', this.questionInfo);
      const { companyId, title, content } = this.questionInfo;

      const res = await addQuestion({
        companyId,
        title,
        content,
        tags: 'consequat Lorem amet deserunt consectetur',
        uid: '76',
      });

      console.log('res', res);
      // 添加成功之后执给点提示
      const { statusText, data } = res;
      if (statusText === 'Created') {
        ElMessage({
          message: '添加到成功',
          type: 'success',
        });
        // 关闭弹窗
        this.showAddDialog = false;
        // 清空表单

        this.questionInfo = {
          companyName: '',
          companyId: '',
          title: '',
          content: '',
          tags: '',
          uid: '',
        };
      }
    },
    handleUploadImage(event, insertImage, files) {
      console.log('files', files);
      // 如何实现把一个 file对象上传到服务器
      const uploadinfo = new FormData();
      uploadinfo.append('type', '2205');
      uploadinfo.append('file', files[0]);
      axios.post('http://www.wzsqyg.com/attachment/upload', uploadinfo).then((res) => {
        console.log('上传的结果', res);
        //  insertImage执行这个方法可以把一个图片链接 插入到文本当中
        insertImage({
          url: res.data.msg,
          desc: res.data.msg.split('/').pop(),
          // width: 'auto',
          // height: 'auto',
        });
      });
    },
    // 使用防抖列优化获取列表的操作
    getList: _.debounce(async function () {
      const queryData = {};
      // 如果当前关键字有输入的话 我们就可以把它当成参数之一执行请求
      if (this.keyword) queryData.title = this.keyword;

      const res = await getQuestList({
        $limit: this.limit,
        $skip: this.skip,
        ...queryData,
      });
      console.log('getList', res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    }, 300),
    formatTime(_d, str) {
      return dayjs(_d).format(str);
    },
  },
};
</script>

<style scoped></style>
